package com.wontube.smr.dao.bo;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;

import com.wontube.core.dao.mybatis.QueryExample;
import com.wontube.smr.client.model.po.DeviceExpert;
import com.wontube.smr.dao.mapper.DeviceExpertMapper;
import com.wontube.smr.pub.DefaultDBHelper;


/**
 * @author yuechao
 *
 */
public final class DeviceExportDao {
	private DeviceExportDao() {
	}
	
	public static DeviceExpert getExpert(String domain, String sysId) {
		if (domain.startsWith("https://")) {
			domain = domain.substring("https://".length());
		}
		
		if (domain.startsWith("http://")) {
			domain = domain.substring("http://".length());
		}
		
		if (domain.startsWith("www.")) {
			domain = domain.substring("www.".length());
		}
		
		QueryExample ex = new QueryExample();
		ex.or().addCriterion("device_expert.domain = ", domain)
			.addCriterion("device_expert.sys_id = ", sysId);
		SqlSession session = DefaultDBHelper.getSqlSession(true);
		try {
			DeviceExpertMapper mapper = session.getMapper(DeviceExpertMapper.class);
			List<DeviceExpert> experts = mapper.selectByExample(ex, new RowBounds(0, 1));
			if (experts.size() > 0) {
				return experts.get(0);
			}
		} finally {
			session.close();
		}
		
		return null;
	}
	public static List<DeviceExpert> getAllExpert(){
		SqlSession session = DefaultDBHelper.getSqlSession(true);
		try {
			DeviceExpertMapper mapper = session.getMapper(DeviceExpertMapper.class);
			QueryExample ex = new QueryExample();
			ex.setOrderByClause("sys_id");
			return mapper.selectByExample(ex);
		} finally {
			session.close();
		}
	}
	public static boolean saveOrUpdateDevice(DeviceExpert device){
		SqlSession session = DefaultDBHelper.getSqlSession(true);		
		try {
			DeviceExpertMapper mapper = session.getMapper(DeviceExpertMapper.class);
			DeviceExpert temp = mapper.selectByPrimaryKey(device.getId());
			int aff = 0;
			if(temp != null){
				aff = mapper.updateByPrimaryKey(device);
			}else{
				aff = mapper.insert(device);
			}
			return aff == 1;
		} finally {
			session.close();
		}
	}
	public static boolean deleteDevice(String pk){
		SqlSession session = DefaultDBHelper.getSqlSession(true);
		try {
			DeviceExpertMapper mapper = session.getMapper(DeviceExpertMapper.class);
			int aff = mapper.deleteByPrimaryKey(pk);
			return (aff == 1);
		} catch (Exception e) {
			return false;
		}finally{
			session.close();
		}
	}
	public static DeviceExpert searchDeviceByPK(String pk){
		SqlSession session = DefaultDBHelper.getSqlSession(true);
		try{
			DeviceExpertMapper mapper = session.getMapper(DeviceExpertMapper.class);
			DeviceExpert de = mapper.selectByPrimaryKey(pk);
			return de;
		}finally{
			session.close();
		}
	}
}
